package com.guoxin.designpattern.chapter4.thread;

import com.guoxin.designpattern.chapter4.thread.LifeCycleListener;
import com.guoxin.designpattern.chapter4.thread.ObserverRunnable;

import java.util.List;

/**
 * @author guoxin
 * @date 2019/9/3
 */
public class ThreadLifeCycleObserver implements LifeCycleListener {

    private final Object lock = new Object();

    public void concurrentQuery(List<String> ids){
        if(ids == null || ids.isEmpty()){
            return;
        }
        ids.forEach(i-> new Thread(new ObserverRunnable(this) {
            @Override
            public void run() {
                try {
                    notifyChange(new RunnableEvent(RunningState.RUNNING,Thread.currentThread(),null));
                    System.out.println("query for the id "+i);
                    Thread.sleep(1000);
                    notifyChange(new RunnableEvent(RunningState.DONE,Thread.currentThread(),null));
                } catch (InterruptedException e) {
                    notifyChange(new RunnableEvent(RunningState.ERROR,Thread.currentThread(),e));
                }
            }
        }).start());
    }
    
    @Override
    public void onEvent(ObserverRunnable.RunnableEvent event) {
        synchronized (lock){
            System.out.println("The runnable ["+event.getThread().getName()+"] data changed and state is ["+event.getState()+"]");
            if(event.getThrowable() != null){
                System.out.println("The runnable ["+event.getThread().getName()+"] process failed.");
            }
        }
    }

}
